<template>
	<view class="container" :class="{ 'pad-mode': isPad }">
		<view class="login-box">
			<view style="display: flex;justify-content: center;align-items: center;flex-direction: column;">
				<image class="logo" src="/static/logo.png" mode="aspectFit" />
				<text class="logo-text">衣勾选·门店端</text>
			</view>
			<form @submit="handleSubmit">
				<view class="input-group">
					<view class="input-row">
						<image class="input-icon" src="/static/login_icon_phone.png" mode="aspectFit" />
						<input class="input" type="text" v-model="form.deliveryPersonnelPhone" placeholder="用户名"
							placeholder-class="placeholder" :disabled="isLocked" />
					</view>
					<div class="divider" />
					<view class="input-row">
						<image class="input-icon" src="/static/login_icon_pwd.png" mode="aspectFit" />
						<input class="input" type="password" v-model="form.password" placeholder="密码"
							placeholder-class="placeholder" :disabled="isLocked" />
					</view>
					<!-- 验证码区域 -->
					<div class="divider" v-if="showCaptcha" />
					<view class="input-row captcha-row" v-if="showCaptcha">
					<input class="input captcha-input" type="text" v-model="form.captcha" placeholder="验证码"
							placeholder-class="placeholder" maxlength="4" style="margin-left: 10rpx;" />
						<captcha-canvas
							ref="captcha"
							:width="120"
							:height="40"
							:length="4"
							@update="onCaptchaUpdate"
						/>
					
					</view>
				</view>
				<button :loading="isLoading" class="submit-btn" form-type="submit" :disabled="isLocked">
					{{ submitBtnText }}
				</button>
				<!-- 锁定提示 -->
				<view class="lock-tip" v-if="isLocked">
					<text class="lock-text">账户已锁定，请{{ lockRemainingTime }}秒后重试</text>
				</view>
			</form>
		</view>
		
		<!-- 底部双语提醒 -->
		<view class="footer-notice">
			<view class="notice-content">
				<text class="notice-text-cn">仅适于公司内部使用</text>
				<text class="notice-text-en">For Internal Staff Use Only</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		personnelLogin
	} from '@/api/index.js'
	import loginSecurity from '@/utils/security.js'
	import CaptchaCanvas from '@/components/base/captcha-canvas.vue'
	export default {
		components: { CaptchaCanvas },
		data() {
			return {
				form: {
					deliveryPersonnelPhone: '',
					password: '',
					captcha: '' 
				},
				isPad: false,
				isLoading: false,
				// 防暴力破解相关
				isLocked: false, // 是否锁定
				lockRemainingTime: 0, // 剩余锁定时间
				lockTimer: null, // 锁定计时器
				// 验证码相关
				showCaptcha: false, // 是否显示验证码
				captchaText: '', // 验证码文本
				submitBtnText: '登 录',
				// 设备标识
				deviceId: ''
			}
		},
		mounted() {
			this.checkDeviceType();
			uni.onWindowResize(() => this.checkDeviceType());
			this.initLoginProtection();
			// 清理过期数据
			loginSecurity.cleanupExpiredData();
		},
		beforeDestroy() {
			if (this.lockTimer) {
				clearInterval(this.lockTimer);
			}
		},
		methods: {
			checkDeviceType() {
				const {
					windowWidth
				} = uni.getSystemInfoSync();
				this.isPad = windowWidth >= 768;
			},
			
			// 初始化登录保护
			initLoginProtection() {
				// 获取设备标识
				this.deviceId = loginSecurity.getDeviceFingerprint();
				
				// 检查是否被锁定
				if (loginSecurity.isLocked(this.deviceId)) {
					this.isLocked = true;
					this.lockRemainingTime = loginSecurity.getRemainingLockTime(this.deviceId);
					this.startLockTimer();
				}
				
				// 检查是否需要显示验证码
				const attempts = loginSecurity.getAttempts(this.deviceId);
				if (attempts >= 3) {
					this.showCaptcha = true;
				}
				
				// 如果显示验证码，生成验证码
				if (this.showCaptcha) {
					this.generateCaptcha();
				}
			},
			
			// 重置登录保护状态
			resetLoginProtection() {
				this.isLocked = false;
				this.showCaptcha = false;
				this.form.captcha = '';
				this.submitBtnText = '登 录';
				loginSecurity.unlockAccount(this.deviceId);
			},
			
			// 开始锁定计时器
			startLockTimer() {
				if (this.lockTimer) {
					clearInterval(this.lockTimer);
				}
				
				this.lockTimer = setInterval(() => {
					this.lockRemainingTime = loginSecurity.getRemainingLockTime(this.deviceId);
					if (this.lockRemainingTime <= 0) {
						clearInterval(this.lockTimer);
						this.resetLoginProtection();
					}
				}, 1000);
			},
			
			// 增加登录尝试次数
			incrementLoginAttempts() {
				const result = loginSecurity.incrementAttempts(this.deviceId);
				
				// 记录安全事件
				loginSecurity.logSecurityEvent('login_attempt', {
					username: this.form.deliveryPersonnelPhone,
					attempts: result.attempts,
					deviceId: this.deviceId
				});
				
				// 检查是否需要显示验证码
				if (result.showCaptcha && !this.showCaptcha) {
					this.showCaptcha = true;
					this.generateCaptcha();
				}
				
				// 检查是否需要锁定账户
				if (result.isLocked) {
					this.lockAccount();
				}
			},
			
			// 锁定账户
			lockAccount() {
				this.isLocked = true;
				this.lockRemainingTime = loginSecurity.getRemainingLockTime(this.deviceId);
				this.submitBtnText = '账户已锁定';
				
				this.startLockTimer();
				
				// 记录锁定事件
				loginSecurity.logSecurityEvent('account_locked', {
					username: this.form.deliveryPersonnelPhone,
					deviceId: this.deviceId
				});
				
				uni.showToast({
					title: `登录失败次数过多，账户已锁定5分钟`,
					icon: 'none',
					duration: 3000
				});
			},
			
			// 生成验证码
			generateCaptcha() {
				this.captchaText = loginSecurity.generateCaptcha(4);
			},
			
			// 刷新验证码
			refreshCaptcha() {
				this.generateCaptcha();
				this.form.captcha = '';
			},
			
			onCaptchaUpdate(code) {
				this.captchaText = code;
			},
			
			// 验证验证码
			validateCaptcha() {
				if (!this.showCaptcha) return true;
				console.log(this.form.captcha, this.captchaText,207);
				return this.form.captcha.toUpperCase() === this.captchaText;
			},
			
			// 检查登录频率
			checkLoginFrequency() {
				if (!loginSecurity.checkFrequency(this.deviceId)) {
					uni.showToast({
						title: '登录过于频繁，请稍后再试',
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			
			handleSubmit() {
				// 检查是否锁定
				if (this.isLocked) {
					uni.showToast({
						title: `账户已锁定，请${this.lockRemainingTime}秒后重试`,
						icon: 'none'
					});
					return;
				}
				
				// 检查登录频率
				if (!this.checkLoginFrequency()) {
					return;
				}
				
				// 验证表单
				if (!this.form.deliveryPersonnelPhone || !this.form.password) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					});
					return;
				}
				
				// 验证验证码
				if (this.showCaptcha && !this.validateCaptcha()) {
					uni.showToast({
						title: '验证码错误',
						icon: 'none'
					});
					this.incrementLoginAttempts();
					// 刷新验证码
					// this.$refs.captcha.drawCaptcha();
					return;
				}
				
				this.isLoading = true;
				this.submitBtnText = '登录中...';
				
				personnelLogin(this.form).then(res => {
					if (res.code == 200) {
						// 登录成功，重置保护状态
						this.resetLoginProtection();
						
						// 记录成功登录事件
						loginSecurity.logSecurityEvent('login_success', {
							username: this.form.deliveryPersonnelPhone,
							deviceId: this.deviceId
						});
						
						this.$store.commit("LOGIN", res.data)
						this.$store.commit("UPDATE_USERINFO", res.data)
						if (res.data.loginType === 2) {
							uni.reLaunch({
								url: "/pages/index/index"
							})
						} else if (res.data.loginType === 1) {
							uni.reLaunch({
								url: "/pages/orderManageRider/orderManageRider"
							})
						}
					} else {
						console.log(res);
						// 登录失败，增加尝试次数
						this.incrementLoginAttempts();
						
						uni.showToast({
							icon: 'none',
							title: res.message
						})
					}
				}).catch(e => {
					// 登录失败，增加尝试次数
					this.incrementLoginAttempts();
					
					uni.showToast({
						icon: 'none',
						title: e || '系统异常'
					})
				}).finally(() => {
					this.isLoading = false;
					this.submitBtnText = '登 录';
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	/* 基础样式 - 移动端优先 */
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background: #f5f7fa; // 纯色背景
		padding: 40rpx;

		.login-box {
			width: 90%;
			max-width: 600rpx;
			background: rgba(255, 255, 255, 0.95);
			border-radius: 24rpx;
			padding: 60rpx 40rpx;
			box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);

			.logo {
				width: 200rpx;
				height: 200rpx;
				margin: 0 auto 30rpx;
			}

			.logo-text {
				font-size: 32rpx;
				color: #111;
				margin-top: 20rpx;
				font-weight: bold;
				margin-bottom: 30rpx;
			}
		}

		.input-group {
			border: 2rpx solid #e0e0e0;
			border-radius: 12rpx;
			overflow: hidden;
			background: #f8fafc;

			.input-row {
				display: flex;
				align-items: center;
				padding: 0 20rpx;
				height: 100rpx;
			}

			.input-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 20rpx;
			}

			.input {
				flex: 1;
				height: 100rpx;
				padding: 0 10rpx;
				font-size: 32rpx;
				background: transparent;
				border: none;
			}

			.divider {
				height: 2rpx;
				background: #e0e0e0;
			}
		}

		.submit-btn {
			margin-top: 60rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: #007aff;
			color: white;
			border-radius: 44rpx;
			font-size: 34rpx;
			letter-spacing: 4rpx;
			border: none;

			&::after {
				border: none
			}
			
			&:disabled {
				background: #cccccc;
				color: #999999;
			}
		}

		.placeholder {
			color: #bdbdbd;
		}
		
		// 验证码样式
		.captcha-row {
			position: relative;
			
			.captcha-input {
				flex: 1;
				padding-right: 120rpx;
			}
			
			.captcha-btn {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				background: #f0f0f0;
				padding: 10rpx 20rpx;
				border-radius: 8rpx;
				border: 2rpx solid #e0e0e0;
				
				.captcha-text {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					letter-spacing: 2rpx;
				}
			}
		}
		
		// 锁定提示样式
		.lock-tip {
			margin-top: 30rpx;
			text-align: center;
			
			.lock-text {
				font-size: 28rpx;
				color: #ff6b6b;
				background: #fff5f5;
				padding: 20rpx 30rpx;
				border-radius: 12rpx;
				border: 2rpx solid #ffebeb;
			}
		}
		
		// 底部双语提醒样式
		.footer-notice {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background: #F5F7FA;
			padding: 30rpx 40rpx;
			box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
			border-top: 2rpx solid #f0f0f0;
			z-index: 100;
			
			.notice-content {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				gap: 8rpx;
			}
			
			.notice-text-cn {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
			}
			
			.notice-text-en {
				font-size: 24rpx;
				color: #666666;
				font-weight: 400;
			}
		}
	}

	/* iPad适配 */
	@media (min-width: 768px) {
		.container.pad-mode {
			padding: 80rpx;

			.login-box {
				padding: 80rpx 60rpx;
				max-width: 800rpx;

				.logo {
					width: 240rpx;
					height: 240rpx;
				}
			}

			.input {
				font-size: 36rpx !important;
			}

			.submit-btn {
				height: 100rpx !important;
				line-height: 100rpx !important;
				font-size: 38rpx !important;
			}
			
			// iPad底部提醒样式
			.footer-notice {
				padding: 40rpx 60rpx;
				
				.notice-text-cn {
					font-size: 32rpx !important;
				}
				
				.notice-text-en {
					font-size: 28rpx !important;
				}
			}
		}
	}
</style>
